package org.atfeihu.springcloud.java8;

import org.atfeihu.springcloud.entity.MyPredicate;
import org.atfeihu.springcloud.entity.MyTestEntity;
import org.junit.jupiter.api.Test;

import java.util.function.Predicate;

/**
 * @author wangfeihu
 * @create 2021/9/5 1:18
 */
public class PredicateDemo {

    @Test
    public void testPredicateObj() {
        /*Predicate<String> predicate = (v1) -> {
            return v1.equals("1");
        };*/

        // 断言字符串（调用predicate的test方法, 返回Boolean值; 判断test参数是否符合lambda表达式定义的规则）
        Predicate<String> predicate = (v1) -> v1.equals("1");
        System.out.println(predicate.test("1"));
        System.out.println(predicate.test("2"));

        // 断言对象
        Predicate<MyTestEntity> predicate2 = te -> te.getId() == 2000L && te.getUsername().equals("admin");
        MyTestEntity entity1 = new MyTestEntity(2000L, "admin");
        MyTestEntity entity2 = new MyTestEntity(2001L, "admin");
        System.out.println(predicate2.test(entity1));
        System.out.println(predicate2.test(entity2));
    }

    @Test
    public void test() {
        MyPredicate myPredicate = new MyPredicate();
        Predicate<MyPredicate> predicate = v -> {
            String path = myPredicate.getPath();
            return v.getPath().startsWith(path.substring(0, path.indexOf("/**")));
        };
        myPredicate.setPath("/payment/get/**");

        System.out.println("predicate('/payment/test'): " +predicate.test(new MyPredicate("/payment/test")));
        System.out.println("predicate('/payment/get/1'): " +predicate.test(new MyPredicate("/payment/get/1")));
    }

    /**
     * Predicate练习
     * 1.and    与
     * 2.or     或
     * 3.negate 非
     */
    @Test
    public void testAndOrNegate() {
        andMethod(s -> s.contains("H"), s -> s.contains("W"));
        orMethod(s -> s.contains("H"), s -> s.contains("W"));
        negateMethod(s -> s.length() > 5);
    }

    private void andMethod(Predicate<String> one, Predicate<String> two) {
        boolean result = one.and(two).test("WangFeiHu");
        System.out.println("是否包含有H和W？" + result);
    }

    private void orMethod(Predicate<String> one, Predicate<String> two) {
        boolean result = one.or(two).test("WangFeiHu");
        System.out.println("是否包含有H或W？" + result);
    }

    private void negateMethod(Predicate<String> predicate) {
        boolean result = predicate.negate().test("WangFeiHu");
        System.out.println("s长度大于5？" + result); // 原本是true, 取非为false
    }

}
